package com.example.config;

import com.example.pojo.User;
import com.example.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author liyan
 */
public class UserRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    /**
     * 授权
     *
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //设置授权规则
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        // 获取当前用户数据
        User user = (User)principals.getPrimaryPrincipal();
        // 添加许可
        info.addStringPermission(user.getPerms());
        return info;
    }

    /**
     * 认证
     *
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        // 通过前端提交的用户名从数据库获取User数据
        User user = userService.queryUserByName((String) token.getPrincipal());

        // 如果user为null，说明用户名不存在，返回null抛出异常UnknownAccountException
        if (user == null) {
            return null;
        }
        // 反之，返回SimpleAuthenticationInfo，校验密码
        return new SimpleAuthenticationInfo(user, user.getPassword(), "");
    }
}
